﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebWorker.aspx.cs" Inherits="BugSysSolution.HTML5Info.WebWorker" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <a href="http://www.w3school.com.cn/html5/html_5_webworkers.asp" style="color:Red">WebWorker</a>
        web worker 是运行在后台的 JavaScript.他单独开辟了一个通道，不影响页面的任何东西.
        <b style="color:blue">postMessage()</b>方法,是向页面传输数据(这里传输的数据是值类型是支持的,如果传输的是对象没测试过.....理论上应该支持,这样就可以往脚本里注入ajax了和服务器通讯).
        <p>
        由于 web worker 位于外部文件中(可以把他理解为服务器脚本)，它们无法访问DOM和BOM对象.
        </p>
    </div>
    <div>
        <input type="text" id="num1" />
        <input type="text" id="num2" />
        <input type="text" id="num3" />
        <input type="button" value="Add" id="Add"/>
        <input type="button" value="Mult" id="Mult"/>
    </div>

        <input type="text" id="txt1" />
        <input type="text" id="txt2" />
        <input type="button" value="Sum" onclick="sum();" />
        
    </form>
</body>
</html>
<script type="text/javascript">
    var getWorkSupport = function () {
        return typeof (Worker) != undefined ? true : false;
    }

    var isSUpport = getWorkSupport();
    var worker = null;

    var createWorker = function () {
        //alert(isSUpport);
        if (isSUpport) {
            worker = new Worker("webworkers.js");
            worker.onmessage = function (event) {
                document.getElementById("num3").value = event.data;
            }
            worker.onerror = function (event) {
                document.getElementById("num3").value = "第[" + event.lineno + "]行发生错误:" + event.message;
            }
        }
        return;
    }

    document.getElementById("Add").onclick = function () {
        createWorker();
        //alert(worker);
        var x = document.getElementById("num1").value;
        var y = document.getElementById("num2").value;
        var str = "add_" + x + "_" + y;
        worker.postMessage(str);
    }

    function sum()
    {
        document.getElementById("txt2").value = parseInt(document.getElementById("num1").value)+parseInt(document.getElementById("num2").value);
    }

    var num = 0;
    function test() {
        num++;
        document.getElementById("txt1").value = num;
    }
    
    window.setInterval(function () { test(); }, 1000);

    document.getElementById("Mult").onclick = function () {
        createWorker();
        var x = document.getElementById("num1").value;
        var y = document.getElementById("num2").value;
        var str = "mult_" + x + "_" + y;
        worker.postMessage(str);
    }
</script>
